#include<unistd.h>
#include<iostream>
#include<pthread.h>
#include<vector>

#define MAX 3

//互斥锁初始化
pthread_mutex_t mute =PTHREAD_MUTEX_INITIALIZER;
//使用条件锁变量
pthread_cond_t cond =PTHREAD_COND_INITIALIZER;

int date=10;

class My_Pthread
{
public:
    My_Pthread(pthread_t id,int name)
    :_id(id),_name(name)
    {}

    //线程ID
    pthread_t _id=0;
    //线程名
    int _name;
};

//线程任务函数
void* handle(void* arg)
{
    pthread_detach(pthread_self());
    //强转
    My_Pthread* ptr=(My_Pthread*)arg;

    while(true)
    {
        pthread_mutex_lock(&mute);
        if(date>0)
        {
            //线程等待
            pthread_cond_wait(&cond,&mute);
            if(date>0)
            {
                std::cout<<"线程编号:"<<(ptr->_id)<<"："<<"date:"<<date<<std::endl;
                date--;
                //释放锁
                pthread_mutex_unlock(&mute);

            }
        }
        else
        {
            //释放锁
            pthread_mutex_unlock(&mute);
            break;
        }
    }

    return NULL;
}

int main()
{
    //用指针来存取线程信息
    std::vector<My_Pthread*> pthread_pointer;

    for(int i=1;i<=MAX;i++)
    {
        pthread_t id;
        //线程执行任务
        My_Pthread* ptr=new My_Pthread(id,i);
        //存储线程数据
        pthread_pointer.push_back(ptr);

        pthread_create(&id,NULL,handle,(void*)ptr);
        ptr->_id=i;
    }
    //唤醒线程
    int count=20;
    while(count--)
    {
        usleep(1000);
        int d=pthread_cond_signal(&cond);
        std::cout<<"唤醒成功！"<<std::endl;
    }


    // //线程等待
    // for(int i=0;i<MAX;i++)
    // {
    //     void* ptr;
    //     pthread_join(pthread_pointer[i]->_id,NULL);
    //     //std::cout<<(((My_Pthread*)ptr)->_name)<<"："<<(((My_Pthread*)ptr)->_id)<<std::endl;
    // }
    //回收空间
    for(int i=0;i<MAX;i++)
    {
        delete pthread_pointer[i];
    }

    return 0;
}